package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.management.snmp.jvmmib.JvmThreadInstanceTableMeta;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    SetmealDishService sdService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时保存口味
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功!");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //分页
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //查询
        dishService.page(dishPage,queryWrapper);

        //属性拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //拷贝查询的信息（records）
        List<Dish> dishes = dishPage.getRecords();


        List<DishDto> dishDtos = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();

            String categoryName = categoryService.getById(categoryId).getName();
            if(categoryName!=null){
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> getOne(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功！");
    }

    @PostMapping("/status/{status}")
    public R<String> changeSale(@PathVariable("status") int status,String[] ids){
        for (String id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("状态修改成功！");
    }

    @DeleteMapping
    public R<String> delete(Long []ids){
        int r = 0;
        int s = 0;
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getDishId,id);
            List<SetmealDish> list = sdService.list(queryWrapper);
            //没关联套餐才能删除
            if(list.isEmpty()){
                //如果停售才删除
                if(dishService.getById(id).getStatus()==0){
                    dishService.removeById(id);
                }else {
                    //起售了几个
                    s++;
                }
            }else {
                //关联了几个
                r++;
            }
        }
        if(r>0&&r==ids.length){
            return R.error("所选菜品关联了套餐！");
        }else {
            if(s>0&&s==ids.length){
                return R.error("所选菜品未停售！");
            }
            return R.success("删除成功！");
        }

    }

    /**
     * 根据类别获取菜列表
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List> list(Dish dish){
        List<DishDto> dishDtos = dishService.listByCategory(dish);
        return R.success(dishDtos);
    }
}
